<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.util.List" %>
<%@ page import="javax.jdo.PersistenceManager" %>
<%@ page import="com.google.appengine.api.datastore.Key" %>
<%@ page import="com.google.appengine.api.datastore.KeyFactory" %>
<%@ page import="com.google.appengine.api.users.User" %>
<%@ page import="com.google.appengine.api.users.UserService" %>
<%@ page import="com.google.appengine.api.users.UserServiceFactory" %>
<%@ page import="eatpoopyoucat.EnumState" %>
<%@ page import="eatpoopyoucat.EpycGame" %>
<%@ page import="eatpoopyoucat.EpycMessage" %>
<%@ page import="eatpoopyoucat.EpycPicture" %>
<%@ page import="eatpoopyoucat.PMF" %>

<html>
	<head>
		<link type="text/css" rel="stylesheet" href="/stylesheets/main.css" />
	</head>

	<body>
<%
UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser();
if (user != null) {
 %>
 		<p>Hello, <%= user.getNickname() %>! (You can
		<a href="<%= userService.createLogoutURL(request.getRequestURI()) %>">sign out</a>.)</p>
 <%
	PersistenceManager pm = PMF.get().getPersistenceManager();
 
    if ( pm == null ) throw new RuntimeException( "pm is null" );
 	
 	try {
		// Something in here does not work correctly...
		
		String gid = request.getParameter( "gid" );
		
		if ( gid == null ) throw new RuntimeException( "gid is null" );
		
		int gameID = Integer.parseInt( gid );
 		Key k = KeyFactory.createKey(EpycGame.class.getSimpleName(), gameID);
		
		if ( k == null ) throw new RuntimeException( "k is null" );
		
		EpycGame game = pm.getObjectById(EpycGame.class, k);
		
		if (game == null) throw new RuntimeException( "game is null" );
		
		// TODO Prevent users from playing out of turn...
		// if (game.getCurrentUser().getEmail() != user.getEmail()) throw new RuntimeException( "It's not your turn yet!" );
		
		EnumState state = game.getCurrentState();
		switch (state) {
			case TEXT: EpycMessage message = pm.getObjectById(EpycMessage.class, game.getLastContentID());
%>
		<p>You're viewing game <%= game.getKey() %>.</p>
		<p><%= message.getMessage() %></p>
<%
				break;
			case PICTURE: EpycPicture picture = pm.getObjectById(EpycPicture.class, game.getLastContentID());
%>
		<p><%= picture.getImageUrl() %></p>
<%
				break;
			case FINISHED: // display everything i guess...
				break;
			default: // do something special?
				break;
		}
 	} catch ( Throwable e) {
 		e.printStackTrace();
 %>
 		<p><%= e.getMessage() %></p>
 <%
 	} finally {
		pm.close();
 	}
} else {
	%>
		<p>Please log in to use this form. <a href="<%= userService.createLoginURL(request.getRequestURI()) %>">Sign in</a></p>
<%
}
%>
	</body>
</html>